package stack.be.touch.ui;

import greendroid.app.GDListActivity;
import greendroid.widget.NormalActionBarItem;
import greendroid.widget.ActionBarItem.Type;

import java.util.ArrayList;
import java.util.List;

import net.sf.stackwrap4j.StackWrapper;
import net.sf.stackwrap4j.entities.Question;
import net.sf.stackwrap4j.enums.Order;
import net.sf.stackwrap4j.http.HttpClient;
import net.sf.stackwrap4j.query.QuestionQuery;
import stack.be.touch.R;
import stack.be.touch.adapter.QuestionsPageAdapter;
import stack.be.touch.dto.QuestionDTO;
import stack.be.touch.utils.Const;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.AbsListView.OnScrollListener;

public class QuestionsPage extends GDListActivity implements OnClickListener, OnScrollListener {
	
	private StackWrapper mStacks;
	private String mQueryType;
	private String mEndpoint;
	private String mUserName;
	private int mPage = 1;
	private int mPageSize;
	private String mInTitle;
	private ArrayList<String> mTagged;
	private boolean mNoMoreQuestions = false;
	private boolean mIsRequestOngoing = true;
	private int mSort = -1;
	private Order mOrder = Order.DESC;
	private boolean isStartActivityForResult = false;
	
	private List<Question> mQuestions;
	private QuestionsPageAdapter mAdapter;
	private View mLoadingView;
	
	
	@Override
	protected void onCreate(Bundle inState) {
		super.onCreate(inState);
		setActionBarContentView(R.layout.questions);
		
		getActionBar().setTitle("All Questions");
		addActionBarItem(Type.Refresh, R.id.action_bar_refresh);
        addActionBarItem(getActionBar()
                .newActionBarItem(NormalActionBarItem.class)
                .setDrawable(R.drawable.ic_title_export)
                .setContentDescription(R.string.gd_export), R.id.action_bar_export);
		
		HttpClient.setTimeout(Const.NET_TIMEOUT);
		mPageSize = Const.getPageSize(this);
		
		if (Intent.ACTION_PICK.equals(getIntent().getAction())) isStartActivityForResult = true;
		
		Uri data = getIntent().getData();
		mQueryType = data.getPathSegments().get(0);
		mEndpoint = data.getQueryParameter("endpoint");
		
		mStacks = new StackWrapper(mEndpoint, Const.APIKEY);
		
		if (inState == null) {
			mQuestions = new ArrayList<Question>();
		}else{
			mQuestions = (ArrayList<Question>)inState.getSerializable("mQuestions");
			mPage = inState.getInt("mPage");
			if (inState.getBoolean("isAsc")) mOrder = Order.ASC;
			mIsRequestOngoing = false;
		}
		mAdapter = new QuestionsPageAdapter(this, mQuestions, this);
		mLoadingView = View.inflate(this, R.layout.item_loading, null);
		getListView().addHeaderView(mLoadingView);
		setListAdapter(mAdapter);
		getListView().setOnScrollListener(this);
		
		if (inState == null) new GetQuestionTask().execute();
		else getListView().setSelection(inState.getInt("scroll"));
		
	}
	
	private void setLoading(boolean loading) {
		getListView().removeFooterView(mLoadingView);
		if (loading) getListView().addFooterView(mLoadingView, null, false);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putSerializable("mQuestions", (ArrayList<Question>) mQuestions);
		outState.putInt("mPage", mPage);
		outState.putBoolean("isAsc", mOrder.equals(Order.ASC));
		outState.putInt("scroll", getListView().getFirstVisiblePosition());
	}
	
	private class GetQuestionTask extends AsyncTask<Void, Void, List<Question>> {
		
		private Exception mException;
		
		@Override
		protected void onPreExecute() {
			setLoading(true);
			mIsRequestOngoing = true;
		}
		
		@Override
		protected List<Question> doInBackground(Void... arg0) {
			try {
				if (mQueryType.equals(QuestionDTO.TYPE_ALL)) {
					QuestionQuery query = new QuestionQuery();
					query.setComments(false).setBody(false).setAnswers(false).setPageSize(mPageSize).setPage(mPage);
					query.setOrder(mOrder);
					return mStacks.listQuestions(query);
				}
			} catch (Exception e) {
				mException = e;
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(List<Question> result) {
			if (isFinishing()) return;
			mIsRequestOngoing = false;
			getListView().removeHeaderView(mLoadingView);
			getListView().removeFooterView(mLoadingView);
			if (mException != null) {
				new AlertDialog.Builder(QuestionsPage.this)
					.setTitle(R.string.title_error)
					.setMessage(R.string.questions_fetch_error)
					.setCancelable(false)
					.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					}).create().show();
				Log.e(Const.TAG, "Failed to get questions", mException);
			}else{
				if (mPage == 1) mQuestions.clear();
				if (result.size() < mPageSize) {
					mNoMoreQuestions = true;
					setLoading(false);
				}
				mQuestions.addAll(result);
				mAdapter.notifyDataSetChanged();
				if (mQuestions.size() == 0) {
					findViewById(R.id.empty).setVisibility(View.VISIBLE);
					getListView().setVisibility(View.GONE);
				}
			}
			
		}
		
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		if (!isStartActivityForResult) {
			String uri = "betouch://question" +
					"?endpoint=" + Uri.encode(mEndpoint) +
					"&qid=" + id;
			Intent i = new Intent(QuestionsPage.this,QuestionAnswerPage.class);
			i.setData(Uri.parse(uri));
			startActivity(i);
		}else{
			Question q = mQuestions.get(position);
			Intent i = new Intent();
			i.putExtra("id", q.getPostId());
			i.putExtra("title", q.getTitle());
			i.putExtra("tags", q.getTags().toArray());
			i.putExtra("score", q.getScore());
			i.putExtra("answers", q.getAnswerCount());
			i.putExtra("views", q.getViewCount());
			i.putExtra("accepted", q.getAcceptedAnswerId());
			setResult(RESULT_OK, i);
			finish();
		}
	}
	
	

	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		
	}

	public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
	}

	public void onScrollStateChanged(AbsListView arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}// CLASS
